package chan.com.mvplib.factory;

import chan.com.mvplib.presenter.BaseMvpPresenter;
import chan.com.mvplib.view.BaseMvpView;

/**
 * Created by chen on 2017/12/25.
 */
public class PresenterMVPFactoryImpl<V extends BaseMvpView, P extends BaseMvpPresenter<V>> implements PresenterMvpFactory<V, P> {

    private final Class<P> mPresenterClass;

    public static <V extends BaseMvpView, P extends BaseMvpPresenter<V>> PresenterMVPFactoryImpl<V, P> createFactory(Class<?> viewClazz) {
        CreatePresenter annotation = viewClazz.getAnnotation(CreatePresenter.class);
        Class<P> aClass = null;
        if (annotation != null) {
            aClass = (Class<P>) annotation.value();
        }
        return aClass == null ? null : new PresenterMVPFactoryImpl<V, P>(aClass);
    }

    private PresenterMVPFactoryImpl(Class<P> presenterClass) {
        this.mPresenterClass = presenterClass;
    }

    @Override
    public P createMvpPresenter() {
        try {
            return mPresenterClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("presenter 创建失败! 检查是否声明了@CreatePresenter(xxx.clazz)注解");
        }
    }
}
